/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  ScrollView,
  TouchableOpacity,
  TouchableHighlight,
  ToolbarAndroid,
  Dimensions,
  BackHandler,
  Platform,
  ListView,
  NativeModules,
} from 'react-native';

import Common from '../../component/common';
import ScreenUtils from '../../component/ScreenUtils';
import ToolbarComponent from '../../component/ToolbarComponent';

import SubscriptionItem from '../me/part/subscriptionItem';
import InfoItem from '../me/part/infoItem';
import VarietyItem from '../me/part/varietyItem';

import Loading from '../../component/loading';
import LoadError from '../../component/loadError';

import Toast from 'react-native-root-toast';

const wechat=require('../../images/wechat.png');
const weibo=require('../../images/weibo.png');
const web=require('../../images/newspaper.png');

import Article from '../home/article'; 

export default class infoSearch extends Component {
  constructor(props) {
    super(props);
    this.state = {
    	dataSource: new ListView.DataSource({
        	rowHasChanged: (row1, row2) => row1 !== row2,
      	}),
      	keywords: this.props.did,
      	loading: true,
		success: false,
      	nowpage:1,
      	pagesize:20,
      	footer:0,
      	error:false,
      	noMoreData:false,
    };
    this.fetchData = this.fetchData.bind(this);
    this.totalList = [];
  }
  
  componentWillMount() {  
    if (Platform.OS === 'android') {  
      BackHandler.addEventListener('hardwareBackPress',() => Common.onBack(this));  
    }  
  }  
  componentWillUnmount() { 
  	this.timer && clearTimeout(this.timer);
    if (Platform.OS === 'android') {  
      BackHandler.removeEventListener('hardwareBackPress', () => Common.onBack(this));  
    }  
  } 
  componentDidMount(){
  	totalList = [];
  	this.fetchData();
  }
  // fetchData(){
  //     this.setState({
  //       loadingMoreData:false,
  //     });
  //   let params = {
  //     "keywords": this.state.keywords,
  //     "nowpage": this.state.nowpage,
  //     "pagesize": this.state.pagesize
  //   }
  //   Common.paging(params,"/search/newsList",(responseData) => {
  //     // var responseData = Common.page("", responseData);
  //       if(responseData.result.length <= this.state.pagesize && this.state.nowpage == responseData.ap){
  //         this.setState({
  //           noMoreData:true,
  //         })
  //       }
  //       for (var i=0; i < responseData.result.length; i++) {  
  //             totalList.push( responseData.result[i] );  
  //           }
  //       this.setState({
  //       dataSource:this.state.dataSource.cloneWithRows( totalList),
  //       nowpage:this.state.nowpage+1,
  //       dataLength:responseData.total,
  //       totalPage:responseData.ap,
  //       loading: false,
  //       success: true,
  //       loadingFail:false,
  //       loadingMoreData:true,
  //     })
  //     },() => {
  //       if(this.state.nowpage===1){
  //         this.setState({
  //       loading: false,
  //       success: false,
  //       errorMessage: "请求失败",
  //       loadingMoreData:true,
  //     })
  //       }else{
  //         this.setState({
  //       loadingFail: true,
  //       loadingFailText:"加载失败，点我重新加载",
  //       loadingMoreData:true,
  //     })
  //       }
  //     },() => {
  //       if(this.state.nowpage===1){
  //           this.setState({
  //         loading: false,
  //         success: false,
  //         errorMessage: "网络错误",
  //         loadingMoreData:true,
  //       })
  //         }else{
  //           this.setState({
  //         loadingFail: true,
  //         loadingFailText:"加载失败，点我重新加载",
  //         loadingMoreData:true,
  //       })
  //         }
  //     });
  // }
  fetchData(){
  	  this.setState({
  	  	loadingMoreData:false,
  	  });
	  let formData = new FormData();
	  	formData.append("keywords",this.state.keywords);
	  	formData.append("nowpage",this.state.nowpage);
	  	formData.append("pagesize",this.state.pagesize);
	    Common.fetchData("post", "/search/newsList", formData, (resp) => {
        var responseData = Common.page("listResult", resp);
        this.totalList = this.totalList.concat(responseData.result);
	    	this.setState({
  				dataSource:this.state.dataSource.cloneWithRows(this.totalList),
  				nowpage:responseData.np+1,
  				dataLength:responseData.total,
  				totalPage:responseData.ap,
          noMoreData: responseData.noMoreData,
  				loading: false,
  				success: true,
  				loadingFail:false,
  				loadingMoreData:true,
  			})
	    },() => {
	      if(this.state.nowpage===1){
	      	this.setState({
				loading: false,
				success: false,
				errorMessage: "请求失败",
				loadingMoreData:true,
			})
	      }else{
	      	this.setState({
				loadingFail: true,
				loadingFailText:"加载失败，点我重新加载",
				loadingMoreData:true,
			})
	      }
	    },() => {
		    if(this.state.nowpage===1){
		      	this.setState({
					loading: false,
					success: false,
					errorMessage: "网络错误",
					loadingMoreData:true,
				})
	      	}else{
		      	this.setState({
					loadingFail: true,
					loadingFailText:"加载失败，点我重新加载",
					loadingMoreData:true,
				})
	      	}
	    });
  }
  _loadingMoreData(event){
  	if(!this.state.noMoreData && this.state.loadingMoreData){
  		this.fetchData();
  		
  	}
  }
  
  refreshData(){
  	this.setState({
  		loadingFailText:"加载中...."
  	})
  	this.loadingAgain = setTimeout(() => {
  		this.fetchData();
  	},1000)
  }
  linking(val) {
    if(Platform.OS == 'ios'){
      NativeModules.JsAndroid.openUrl(val.url);
    }else{
      // Common.onForward(this, Article, val, 5);
      Common.onForward(this,Article,val,5);
    }
  }
  renderInfoItems(data,sectionID,rowID) {
  	let sourceImage ;
  	var mydata = Common.keyWordHighlight(data.title);
  	switch(data.scrabbleType){
  		case 'wechat':
  			sourceImage = wechat;
  			break;
  		case 'web':
  			sourceImage = web;
  			break;
  		default :
  			sourceImage = weibo;
  			break;
  	}
    return (
      <TouchableHighlight underlayColor="#fafafa" delayPressIn={100} style ={styles.InfoItemContainer} onPress={() => this.linking({title:Common.cancelHightlight(data.title),url:data.url,id:data.id})}>
      	<View style={{flex:1,flexDirection:"column",justifyContent:"space-between",}}>
          <View style={styles.infoTitleWrap} >
      			<Text style={styles.infoTitle} numberOfLines ={1}>
      				{
      		          	mydata.map((item,i)=>{
      		          		if(item.hightLight){
      		          			return(
      		          				<Text key={i} style={{color:"red"}}>{item.data}</Text>
      		          			)
      		          		}else{
      		          			return(
      		          				<Text key={i}>{item.data}</Text>
      		          			)
      		          		}
      		          	})
      	        	}
      			
      			</Text>
      		</View>
      		<View style={styles.infoAbout}>
      			<View style={styles.infoContent}>
        				<Image style={styles.infoAboutImage} source = {sourceImage}/> 
        				<Text style={styles.infoAboutText}>
        					<Text style={styles.infoText}>{data.company}</Text>
        				</Text>
        			</View>
        			<View style={styles.infoContent}>
        				<Image style={styles.infoAboutImageTimer} source = {require('../../images/timer.png')}/> 
        				<Text style={styles.infoAboutText}>
        					<Text style={styles.infoText}>{Common.beforeTime(data.createTime,5)}</Text>
        				</Text>
        			</View>
        			{
        				data.sourceDegree ? 
        				(
        					parseFloat(data.sourceDegree)>0 ?
        						<View style={styles.infoContent}>
      			  				<Text style={styles.infoAboutText}>
      			  						<Text style={styles.infoText}>{data.sourceDegree}</Text> 阅读
      			  				</Text>
      			  			</View> :null
        				):null
        			}
      		</View>
        </View>
      </TouchableHighlight>
    );
  }
  renderListHeader(){
  	return(
  		<Text style={styles.collectionCategory}>
			<Text>共{String(this.state.dataLength)}条</Text>
		</Text>
  	)
  }
  renderListFooter(){
  	return(
  		<View>
	  		{
				this.state.noMoreData ? <View style={styles.noMoreData}><Text style={styles.noMoreDataText}>数据已全部加载完毕</Text></View>:null
			}
			{
				this.state.loadingFail ? <TouchableOpacity onPress = {this.refreshData.bind(this)} style={styles.noMoreData}><Text style={styles.noMoreDataText}>{this.state.loadingFailText}</Text></TouchableOpacity>:null
			}
		</View>
  	)
  }
  render() {
    return (
      <View style ={styles.subscriptionContainer}>
  	    <ToolbarComponent
          leftItem={{
            title: 'Back',
            layout: 'icon',
            icon: require("../../images/back.png"),
            onPress: () => {
              Common.onBack(this);
            },
          }}
        >
          <View style={styles.toolbarV}>
            <Text style={styles.toolbarT} numberOfLines={1}>搜索结果 - 资讯</Text>
          </View>
        </ToolbarComponent>
		{
      		this.state.loading ?
				<Loading/>
					: (
						this.state.success ?
							<View style={{flex:1}}>
					      		<View style={styles.subscriptionItem}>
							      	<ListView
										dataSource={this.state.dataSource}
										enableEmptySections={true}
									    renderRow={this.renderInfoItems.bind(this)}
									    showsVerticalScrollIndicator ={false}
									    onEndReached={this._loadingMoreData.bind(this)}
									    onEndReachedThreshold={500}
									    renderHeader = {this.renderListHeader.bind(this)}
									    renderFooter = {this.renderListFooter.bind(this)}
									    contentContainerStyle={{marginBottom:ScreenUtils.scaleSize(14),}}
									    scrollRenderAheadDistance = {300}
									    removeClippedSubviews ={true}
									/>
							      	
						      	</View>
					      	</View>
						    : <LoadError reload={this.fetchData} reason={this.state.errorMessage}/>
					)      		
      }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  subscriptionContainer:{
    flex: 1,
  	backgroundColor:"#f6f6f6",
  	flexDirection:"column",
  },
  subscriptionItem:{
  	flex: 1,
  	flexDirection:"column",
  	overflow:"scroll",
  },
  toolbarV: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  toolbarT: {
    color: '#ffffff',
    fontWeight: 'bold',
    fontSize: ScreenUtils.scaleSize(40),
  },
  InfoItemContainer:{
    width:Dimensions.get('window').width,
  	backgroundColor:"#fff",
  	flexDirection:"column",
  	height:ScreenUtils.scaleSize(112),
  	borderBottomWidth:1,
  	borderColor:"#ebebeb",
  	justifyContent:"space-between",
  	paddingLeft:ScreenUtils.scaleSize(30),
  	paddingRight:ScreenUtils.scaleSize(26),
  	paddingTop:ScreenUtils.scaleSize(20),
  	paddingBottom:ScreenUtils.scaleSize(20),
  },
  infoTitle:{
  	fontSize:ScreenUtils.scaleSize(24),
  	color:"#444444",
  },
  infoAbout:{
  	flexDirection:"row",
  	justifyContent:"flex-end",
  },
  infoAboutText:{
  	fontSize:ScreenUtils.scaleSize(22),
  	color:"#9d9d9d",
  	paddingLeft:3,
  },
  infoAboutImageTimer:{
  	width:ScreenUtils.scaleSize(22),
  	height:ScreenUtils.scaleSize(22),
  },
  infoAboutImage:{
  	width:ScreenUtils.scaleSize(22),
  	height:ScreenUtils.scaleSize(18),
  },
  infoContent:{
  	flexDirection:"row",
  	marginLeft:ScreenUtils.scaleSize(20),
  	justifyContent:"center",
  	alignItems:"center",
  },
  deleteWrap:{
  	width:ScreenUtils.scaleSize(132),
  	backgroundColor:"#ff4545",
  	justifyContent:"center",
  	alignItems:"center",
  	borderBottomWidth:1,
  	borderColor:"#ebebeb",
  },
  deleteText:{
  	fontSize:ScreenUtils.scaleSize(26),
  	color:"#fff",
  },
  collectionCategory:{
  	paddingLeft:ScreenUtils.scaleSize(30),
  	fontSize:ScreenUtils.scaleSize(22),
  	color:"#939393",
  	paddingTop:ScreenUtils.scaleSize(14),
  	paddingBottom:ScreenUtils.scaleSize(14),
  	borderBottomWidth:1,
  	borderColor:"#ebebeb",
  },
  Item:{
  	marginTop:ScreenUtils.scaleSize(10),
  	borderTopWidth:1,
  	borderColor:"#ededed",
  },
  noMoreData:{
  	flex:1,
  	justifyContent:"center",
  	alignItems:"center",
  	height:ScreenUtils.scaleSize(150),
  	flexDirection:"row",
  	marginTop:-ScreenUtils.scaleSize(14),
  },
  noMoreDataText:{
  	fontSize:ScreenUtils.scaleSize(18),
  }
});